//
//  DepartTreeView.m
//  gdemm
//
//  Created by 乔明超 on 16/9/25.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "DepartTreeView.h"
#import "Masonry.h"
#import "SVProgressHUD.h"
#import "ASIHTTPRequest.h"
#import "ApiSupport.h"
#import "ToastManager.h"
#import "Utils.h"
#import "DepartTrees.h"
#import "DepartTableViewCell.h"
#import "TreeTableView.h"
#import "Node.h"

@interface DepartTreeView ()<ASIHTTPRequestDelegate>
@property (strong, nonatomic) NSMutableArray *mDepartArray;
@property (strong, nonatomic) TreeTableView *tableview;
@property(nonatomic,strong)NSMutableArray * allNode;
@property(nonatomic,assign)int noid;
@property(nonatomic,assign)int depth;
@property(nonatomic,assign)NSInteger  TreeViewWidth;
@property(nonatomic,assign)NSInteger  TreeViewHeight;
@end
@implementation DepartTreeView

-(instancetype)init{
    if (self = [super init]) {
        if ([DeviceTypeJudge isPadDeviceType]) {
            self.TreeViewWidth = 456;
            self.TreeViewHeight = 700;
            
        }else{
            self.TreeViewWidth = 224*KWidthScale;
            self.TreeViewHeight = 455*KHeightScale;
        }
        self.noid = 0;
        self.depth = 0;
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showWithStatus:@"部门加载中,请等待...."];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[ApiSupport getDeptreeUrl]]];
            request.delegate = self;
            [request startSynchronous];
        });
        
        
    }
    return self;
}

-(NSMutableArray *)mDepartArray{
    if (_mDepartArray == nil) {
        _mDepartArray = [[NSMutableArray alloc]init];
    }
    return _mDepartArray;
}

#pragma mark ASIHTTPRequest代理协议的实现
-(void)requestFailed:(ASIHTTPRequest *)request{
      [ToastManager showColorToast:self WithLable:@"网络异常"];
      [SVProgressHUD dismiss];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeFromSuperview];
    });
}
-(void)requestFinished:(ASIHTTPRequest *)request{
    [SVProgressHUD dismiss];
   NSMutableArray * tempArray = [[NSMutableArray alloc]init];
    NSError *error;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:&error];
    if (array != nil && error == nil) {
        [array enumerateObjectsUsingBlock:^(NSDictionary  * obj, NSUInteger idx, BOOL * _Nonnull stop)
        {
            Node *node = [[Node alloc]initWithPointDic:obj];
            node.depth = 0;
            node.expand = YES;
            node.parentId = -1;
            node.nodeId = self.noid;
            self.noid++;
            [tempArray addObject:node];
        }];
    [self recursiveAllPoints:tempArray];
    }
    //创建Node节点
    NSMutableArray *nodes = [NSMutableArray array];
    [self.allNode enumerateObjectsUsingBlock:^(Node *point, NSUInteger idx, BOOL * _Nonnull stop) {
        Node *node = [[Node alloc] initWithParentId:point.parentId nodeId:point.nodeId name:point.name depth:point.depth expand:point.expand :point.guid];
        [nodes addObject:node];
    }];
    self.mDepartArray = nodes;
    [self initData];
    [self addView];
    [self.tableview reloadData];
}

-(void)addView{
    NSInteger leftMagin = (WINDOWWIDTH - self.TreeViewWidth)/2;
    NSInteger topMagin = (WINDOWHEIGHT - self.TreeViewHeight)/2;
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WINDOWHEIGHT, topMagin)];
    topView.backgroundColor = [Utils UIColorFromHex:0X06060f];
    topView.alpha = 0.5;
    [self addSubview:topView];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, topMagin, leftMagin, self.TreeViewHeight)];
    leftView.backgroundColor =  [Utils UIColorFromHex:0X06060f];
    leftView.alpha = 0.5;
    [self addSubview:leftView];
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,self.TreeViewHeight+topMagin, WINDOWWIDTH, topMagin)];
    bottomView.backgroundColor =  [Utils UIColorFromHex:0X06060f];
    bottomView.alpha = 0.5;
    [self addSubview:bottomView];
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.TreeViewWidth+leftMagin, topMagin, leftMagin, self.TreeViewHeight)];
    rightView.backgroundColor = [Utils UIColorFromHex:0X06060f];
    rightView.alpha = 0.5;
    [self addSubview:rightView];
    UITapGestureRecognizer * tapGestureRecognizerLeft = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureRecognizerHander:)];
    [leftView addGestureRecognizer:tapGestureRecognizerLeft];
    UITapGestureRecognizer * tapGestureRecognizerTop = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureRecognizerHander:)];
    [topView addGestureRecognizer:tapGestureRecognizerTop];
    UITapGestureRecognizer * tapGestureRecognizerRight = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureRecognizerHander:)];
    [rightView addGestureRecognizer:tapGestureRecognizerRight];
    UITapGestureRecognizer * tapGestureRecognizerBottom = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureRecognizerHander:)];
    [bottomView addGestureRecognizer:tapGestureRecognizerBottom
     ];
}


-(void)tapGestureRecognizerHander:(id)gesture{
    
    if ([self.delegate respondsToSelector:@selector(removeDepartView)]) {
        [self.delegate removeDepartView];
    }
}


-(void)initData{
    
    self.tableview = [[TreeTableView alloc] initWithFrame:CGRectMake((WINDOWWIDTH-self.TreeViewWidth)/2, (WINDOWHEIGHT-self.TreeViewHeight)/2, self.TreeViewWidth, self.TreeViewHeight) withData:self.mDepartArray];
    [self addSubview:self.tableview];
}

//递归所有的知识点
-(void)recursiveAllPoints:(NSMutableArray *)nodeArray{
    for (int i = 0;i< nodeArray.count;i++) {
        Node * node = nodeArray[i];
        if (self.allNode.firstObject == node) {
            break;
        }
    
        [self.allNode addObject:node];
        if (node.nodeSonArray.count > 0){
            NSMutableArray *sonPoints = [NSMutableArray array];
            NSArray * array = [NSArray arrayWithArray:node.nodeSonArray];
            [array enumerateObjectsUsingBlock:^(NSDictionary *pointDic, NSUInteger idx, BOOL * _Nonnull stop){
                Node *point = [[Node alloc]initWithPointDic:pointDic];
                point.expand = NO;
                point.nodeId = self.noid;
                self.noid ++;
                point.depth = node.depth+1;
                point.parentId = node.nodeId;
                [sonPoints addObject:point];
            }];
            
            [self recursiveAllPoints:sonPoints];
        }
    }
    
}

-(NSMutableArray *)allNode{
    if (_allNode == nil) {
        _allNode = [[NSMutableArray alloc]init];
    }
    return _allNode;
}

@end
